<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;
use App\Model\Admin\Menus;
use App\Model\Admin\Roles;

class RolesController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Admin $admin;

    #[Inject]
    protected Menus $menus;

    #[Inject]
    protected Roles $roles;


    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**获取角色列表
     * @param RequestInterface $request
     * @param ResponseInterface $response
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function getList(RequestInterface $request,ResponseInterface $response):\Psr\Http\Message\ResponseInterface
    {
        $page = $request->inputs(['page','limit','keyword']);
        $list = $this->roles->where(function ($query) use ($page) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('name', 'like', '%' . $page['keyword'] . '%');
//                $query->orWhere('content', 'like', '%'.$page['keyword'].'%');
            }
            $query->where('is_del',  Common::DEL_SHOW);
        })->orderBy('id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get(['id','name','created_at','menus','updated_at'])->toArray();
        $count = $this->roles->where(function ($query) use ($page) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('name', 'like', '%' . $page['keyword'] . '%');
            }
            $query->where('is_del',  Common::DEL_SHOW);
        })->count();
        return $response->json(['data' => $list, 'total' => $count, 'code' => 200]);
    }

    /**权限详情
     * @param RequestInterface $request
     * @return \Psr\Http\Message\ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function detail(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        try{
            $id = $request->input('id',0,'int');
            $model= $this->roles->where('id',$id)->first(['menus','name'])->toArray();
            $menus =[];
            if($model['menus']){
                $model['menus'] = json_decode($model['menus']);
                $menus =$this->menus->whereIn('id',$model['menus'])->get(['id','label'])->toArray();
            }
            return $this->success($menus);
        }catch(\Exception $e){
             return $this->error();
        }
    }

    /**获取所有角色
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function all(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $list = $this->roles->where('is_del',  Common::DEL_SHOW)->orderBy('id', 'desc')
            ->get(['id','name'])->toArray();
        return $this->success($list);
    }


    /**创建编辑身份
     * @param RequestInterface $request
     * @return \Psr\Http\Message\ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $data = $request->post();
        $save['name']=$data['name'];
        $arr =[];
        if(count($data['menus'])>0){
            foreach($data['menus'] as $v){
                array_push( $arr,$v['id']);
            }
            $save['menus'] = json_encode($arr);
        }
        if (array_key_exists('id',$data) && $data['id'] > 0) {
            $id = $data['id'];
            unset($data['id']);
            if(array_key_exists('updated_at', $data)){
                unset($data['updated_at']);
            }
            $this->roles->where('id', $id)->update($save);
        } else {
            Roles::create($save);
        }
        return $this->success();
    }

    /**删除角色
     * @param RequestInterface $request
     * @return \Psr\Http\Message\ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function del(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $id = $request->input('id',0,'int');
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        $this->roles->where('id',$id)->update(['is_del'=>Common::DEL_HIDE]);
        return $this->success();
    }

}
